package com.icode.syn.ticketSale2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: my_code
 * @Create: 2020-12-09 17:40
 *
 * Lock三步走：
 * 1、new ReentrantLock
 * 2、lock.lock();  //加锁
 * 3、lock.unlock(); //释放锁
 */
public class Ticket {
    private int num = 30;

    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();  //加锁
        try {
            //业务代码
            if (num > 0) {
                System.out.println(Thread.currentThread().getName() + "拿到了第" +
                        num-- + "张票");
            }
        } finally {
            lock.unlock();  //释放锁
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

